﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace PerfAnalyzerLib
{
	public class Counter
	{
		public const int SampleArraySize = 100;

		private CounterInfo _info;
		private double[] _values;
		private double[] _sampledValues;
		private CounterStats _stats;

		public CounterInfo Info { get { return _info; } }
		public CounterStats Stats { get { return _stats; } }
		public double[] SampledValues { get { return _sampledValues; } }

		public double[] Values
		{
			get { return _values; }
			set
			{
				if (null == value || 0 == value.Length)
				{
					throw new NullReferenceException("Cannot assign a null or empty array.");
				}

				_values = value;
				ProcessValues();
			}
		}

		public PerfLog Perflog = null;

		/// <summary>
		/// Constructor.
		/// </summary>
		/// <param name="counterName">Name of the counter.</param>
		public Counter(string counterName)
		{
			if (String.IsNullOrWhiteSpace(counterName))
			{
				throw new ArgumentException("The given string name is null, empty or contains only spaces.");
			}

			_info = new CounterInfo(counterName);
		}

		/// <summary>
		/// Generate statistics and sampled array.
		/// </summary>
		private void ProcessValues()
		{
			_stats = new CounterStats(_values);
			GenerateSampledArray();
		}

		/// <summary>
		/// General Sample Array from the Value array.
		/// </summary>
		private void GenerateSampledArray()
		{
			if (_values.Length <= SampleArraySize)
			{
				_sampledValues = _values;
				return;
			}

			_sampledValues = new double[SampleArraySize];
			var interval = (double)_values.Length / (double)SampleArraySize;

			int start, end = 0;
			for (int i = 0; i < SampleArraySize; i++)
			{
				start = end;
				end = (int) ((i+1)*interval);

				double sum = 0;
				for (int j = start; j < end; j++)
				{
					sum += _values[j];
				}

				_sampledValues[i] = sum/(end - start);
			}
		}
	}
}
